package com.wzh.ojbackenduserservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzh.ojCommon.common.ErrorCode;
import com.wzh.ojCommon.exception.BusinessException;
import com.wzh.ojModel.model.entity.User;
import com.wzh.ojModel.model.enums.UserRoleEnum;
import com.wzh.ojModel.model.vo.UserVO;
import com.wzh.ojbackenduserservice.mapper.UserMapper;
import com.wzh.ojbackenduserservice.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import static com.wzh.ojCommon.constant.UserConstant.ADMIN_ROLE;
import static com.wzh.ojCommon.constant.UserConstant.USER_LOGIN_state;


/**
 * @author Admin
 * @description 针对表【user(用户)】的数据库操作Service实现
 * @createDate 2023-03-31 20:16:56
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

     @Autowired
    private UserMapper userMapper;

    /**
     * 定义盐值，用于混淆密码
     */
    private static final String SALT = "aoKai";

    /**
     * 注册
     * @param userAccount
     * @param userPassword
     * @param checkPassword
     * @return
     */
    @Override
    public Long userRegister(String userAccount, String userPassword, String checkPassword) {
//        校验用户名密码是否符合规范
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "输入两次密码不一致");
        }
        synchronized (userAccount.intern()) {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("userAccount", userAccount);
            Long count = userMapper.selectCount(queryWrapper);
            if (count > 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名重复");
            }
//            加密操作
            String pwd = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
//            插入数据
            User user = new User();
            user.setUserAccount(userAccount);
            user.setUserPassword(pwd);
            boolean save = this.save(user);
            if (!save) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败,数据库出现错误");
            }
//            返回用户id;
            return user.getId();
        }
    }

    /**
     * 登录
     * @param userAccount
     * @param userPassword
     * @return
     */
    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        if (StringUtils.isAnyBlank(userAccount,userPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }
        if (userAccount.length()<4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号错误");
        }

        if (userPassword.length()<8){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码错误");
        }
//        获取加密后的密码
        String pwd = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("userAccount",userAccount);
        queryWrapper.eq("userPassword",pwd);
        User user = userMapper.selectOne(queryWrapper);
        if (user==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户不存在或者密码错误");
        }
        if (user.getIsDelete()==1){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"用户不存在");
        }
//        记录用户的登录态，后续也可以优化，使用jwt+token实现单点登录
        request.getSession().setAttribute(USER_LOGIN_state,user);
        return user;
    }


    /**
     * 获取当前登录用户信息
     * @param request
     * @return
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        User user =(User) request.getSession().getAttribute(USER_LOGIN_state);
        if (user==null||user.getId()==null){
         throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
//        通过数据库查询可以获取当前用户的最新信息
//        此处可以通过缓存进行优化，提高性能
       user = this.query().eq("id", user.getId()).one();
        if (user==null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return user;
    }


    /**
     * 退出登录
     * @param request
     * @return
     */
    @Override
    public Boolean userLogout(HttpServletRequest request) {
        if (request.getSession().getAttribute(USER_LOGIN_state)==null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        HttpSession session = request.getSession();
        session.removeAttribute(USER_LOGIN_state);
        return true;
    }

    /**
     * 判断用户是否为管理员
     * @param request
     * @return
     */

    @Override
    public boolean isAdmin(HttpServletRequest request) {
        // 仅管理员可查询
        Object userObj = request.getSession().getAttribute(USER_LOGIN_state);
        User user = (User) userObj;
        return user != null && ADMIN_ROLE.equals(user.getUserRole());
    }

    @Override
    public boolean isAdmin(User user) {
        return user != null && UserRoleEnum.ADMIN.getValue().equals(user.getUserRole());
    }

    @Override
    public UserVO getUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }




}
